package com.wetech.demo.web3j.controller;

import com.wetech.demo.web3j.service.TokenService;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.util.Map;

@RestController
@RequestMapping("/token")
public class TokenController {

    private final TokenService tokenService;

    public TokenController(TokenService tokenService) {
        this.tokenService = tokenService;
    }

    @PostMapping("/deploy")
    public Map<String, Object> deploy() throws Exception {
        String address = tokenService.deploy();
        return Map.of("contractAddress", address);
    }

    @PostMapping("/mint")
    public Map<String, Object> mint(@RequestBody Map<String, String> req) throws Exception {
        String hash = tokenService.mint(req.get("contract"), req.get("to"), new BigInteger(req.get("amount")));
        return Map.of("txHash", hash);
    }

    @PostMapping("/transfer")
    public Map<String, Object> transfer(@RequestBody Map<String, String> req) throws Exception {
        String hash = tokenService.transfer(req.get("contract"), req.get("to"), new BigInteger(req.get("amount")));
        return Map.of("txHash", hash);
    }

    @GetMapping("/balanceOf")
    public Map<String, Object> balanceOf(@RequestParam String contract, @RequestParam String address) throws Exception {
        return Map.of("balance", tokenService.balanceOf(contract, address));
    }

    @PostMapping("/approve")
    public Map<String, Object> approve(@RequestBody Map<String, String> req) throws Exception {
        String hash = tokenService.approve(req.get("contract"), req.get("spender"), new BigInteger(req.get("amount")));
        return Map.of("txHash", hash);
    }

    @PostMapping("/transferFrom")
    public Map<String, Object> transferFrom(@RequestBody Map<String, String> req) throws Exception {
        String hash = tokenService.transferFrom(req.get("contract"), req.get("from"), req.get("to"), new BigInteger(req.get("amount")));
        return Map.of("txHash", hash);
    }
}
